package com.yxp423.ssmempl.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Description: java类作用描述
 * @Author: yxp
 * @CreateDate: 2019-06-13 10:44
 * @Version: 1.0
 */

@Component
@ServerEndpoint(value = "/webSocket/{id}")
@Slf4j
public class WebSocketService {

	private Session session;

//	private CopyOnWriteArraySet<WebSocket> sessionsSet = new CopyOnWriteArraySet<>();

	//	private ConcurrentHashMap<String,WebSocket> sessionsSet = new ConcurrentHashMap<>();
	private static transient volatile Set<WebSocketService> sessionsSet = ConcurrentHashMap.newKeySet();


	private String userId;

	private List<String> list = new ArrayList<>();

	@OnOpen
	public void onOpen(@PathParam("id") String id, Session session) {


		if (list.size() > 0) {

			for (String s : list) {
				if (!s.equals(id)) {
					this.session = session;
					this.userId = id;
					sessionsSet.add(this);
					list.add(id);
					log.info("[ webSocket信息 ]  有新的用户{}加入，当前连接总数为： {}", id, sessionsSet.size());
				}
			}
		}else {

		this.session = session;
		this.userId = id;
		sessionsSet.add(this);
		list.add(id);
		log.info("[ webSocket信息 ]  有新的用户{}加入，当前连接总数为： {}", id, sessionsSet.size());

		}


	}


	@OnClose
	public void onClose() {

		sessionsSet.remove(this);
		log.info("[ webSocket信息 ]  有连接断开，当前连接总数为： {}", sessionsSet.size());
	}

	@OnMessage
	public void onMessage(String message) {

		log.info("[ webSocket信息 ]  收到客户端信息： {} ", message);
		//广播信息
//		this.sendMessage(message);
		this.sendToAll(message);

	}


	/**
	 * 发送消息
	 *
	 * @param message
	 */
	public void sendMessage(String message) {

		try {
			this.session.getBasicRemote().sendText(message);
		} catch (IOException e) {
			e.printStackTrace();
			log.error("发生错误，{}", e.getMessage());
		}
	}

	/**
	 * 向特定用户发送信息
	 *
	 * @param message
	 * @param userId
	 */
	public void sendToOneUser(String message, String userId) {

		for (WebSocketService socketService : sessionsSet) {

			if (socketService.userId.equals(userId)){

				socketService.sendMessage(message);
			}
		}


	}

	/**
	 * 广播信息
	 *
	 * @param message
	 */
	public void sendToAll(String message) {

		log.info("[ webSocket信息 ]  向所有客户端发送信息： {} ", message);
		for (WebSocketService socket : sessionsSet) {

			socket.sendMessage(message);
		}

	}

}
